let smallScreenExecuted = false; // 用于标记小于768的情况是否已执行
let largeScreenExecuted = false; // 用于标记大于等于768的情况是否已执行
let allowTouchMove = false;
var mySwiper = null;

// 响应式布局调整
function adjustLayout() {
  var width = window.innerWidth;

  if (width < 768) {
    document.querySelector(".process-wrapper").classList.add("process-grid");
    if (!smallScreenExecuted) {
      if (mySwiper) {
        mySwiper.destroy();
      }
      mySwiper = new Swiper(".mySwiper", {
        spaceBetween: 39,
        freeMode: true,
        centeredSlides: true,
        pagination: {
          el: ".swiper-pagination",
          clickable: true,
        },
        slidesPerView: "auto",
      });
      //   mySwiper.slideTo(2);
    }
    smallScreenExecuted = true; // 标记为已执行
    if (largeScreenExecuted) {
      largeScreenExecuted = false; // 如果之前大屏幕逻辑执行过，重置它
    }
  }
  if (width > 768) {
    document.querySelector(".process-wrapper").classList.remove("process-grid");
    if (!largeScreenExecuted) {
      if (mySwiper) {
        mySwiper.destroy();
      }

      mySwiper = new Swiper(".mySwiper", {
        spaceBetween: 39,
        freeMode: true,
        // centeredSlides: true,
        pagination: {
          el: ".swiper-pagination",
          clickable: true,
        },
        slidesPerView: "auto",
      });
      //   mySwiper.slideTo(0);
      mySwiper.allowTouchMove = false;
    }
    largeScreenExecuted = true; // 标记为已执行
    if (smallScreenExecuted) {
      smallScreenExecuted = false; // 如果之前小屏幕逻辑执行过，重置它
    }
  }
  if (width < 1440) {
    if (mySwiper) {
      if (!allowTouchMove) {
        mySwiper.allowTouchMove = true;
        allowTouchMove = true;
      }
    }
  }
  if (width > 1440) {
    if (mySwiper) {
      if (allowTouchMove) {
        mySwiper.allowTouchMove = false;
        allowTouchMove = false;
      }
    }
  }
}

// 页面加载和窗口大小改变时调整布局
window.addEventListener("DOMContentLoaded", adjustLayout);
window.addEventListener("resize", adjustLayout);

// 产品中心 左右切换
document.querySelector(".product-control-prev").onclick = () => {
  const productItems = document.querySelectorAll(".product-item");
  let findIndex = 0;
  productItems.forEach((x, index) => {
    if (x.classList.contains("product-item-active")) {
      findIndex = index;
      x.classList.remove("product-item-active");
    }
  });
  console.log(findIndex, productItems);
  if (findIndex === 0) {
    productItems[productItems.length - 1].classList.add("product-item-active");
  } else {
    productItems[findIndex - 1].classList.add("product-item-active");
  }
};
document.querySelector(".product-control-next").onclick = () => {
  const productItems = document.querySelectorAll(".product-item");
  let findIndex = 0;
  productItems.forEach((x, index) => {
    if (x.classList.contains("product-item-active")) {
      findIndex = index;
      x.classList.remove("product-item-active");
    }
  });
  if (findIndex === productItems.length - 1) {
    productItems[0].classList.add("product-item-active");
  } else {
    productItems[findIndex + 1].classList.add("product-item-active");
  }
};

// 产品点击跳转
const productItemArray = document.querySelectorAll(".product-item");
productItemArray.forEach((item) => {
  item.addEventListener("click", () => {
    window.open(
      "/productDetail?category=榨油设备&position=0&name=ZY/ZX32螺旋榨油机"
    );
  });
});
const mProductCardArray = document.querySelectorAll(".m-product-card");
mProductCardArray.forEach((item) => {
  item.addEventListener("click", () => {
    window.open(
      "/productDetail?category=榨油设备&position=0&name=ZY/ZX32螺旋榨油机"
    );
  });
});
// web设备-产品中心 设备切换
let getTemplate = (title) => {
  return `<div class="product-item product-item-active">
            <div class="product-item-img">
              <img src="/assets/image/index/p.png" alt=""></img>
            </div>
            <div class="product-info">
              <h2 class="product-title">${title}ZY/ZX50螺旋榨油机</h2>
              <div class="product-description">
                ZY/ZX50螺旋榨油机是工业级榨油设备，适用于大型油厂的连续生产线。具有自动化程度高、能耗低、维护简便等特点，是现代化油厂的理想选择。
              </div>
            </div>
          </div>

          <div class="product-item">
            <div class="product-item-img">
              <img src="/assets/image/index/p.png" alt=""></img>
            </div>
            <div class="product-info">
              <h2 class="product-title">${title}A-02螺旋榨油机</h2>
              <div class="product-description">
                适用于大型油厂的连续生产线。具有自动化程度高、能耗低、维护简便等特点，是现代化油厂的理想选择。
              </div>
            </div>
          </div>`;
};

const productListiItems = document.querySelectorAll(".product-list-item");
const productList = document.querySelector(".product-list");
productListiItems.forEach((item) => {
  item.addEventListener("click", () => {
    item.classList.add("active");
    const template = getTemplate(item.innerText);
    document.querySelector(".product-content").innerHTML = template;
    productListiItems.forEach((it) => {
      if (item != it) {
        it.classList.remove("active");
      }
    });

    // 计算滚动位置
    const containerHeight = productList.clientHeight;
    const itemHeight = item.offsetHeight;
    const itemTop = item.offsetTop;
    // 计算目标滚动位置（使当前item居中）
    const targetScrollTop = itemTop - containerHeight / 2 + itemHeight / 2;
    // 使用平滑滚动
    productList.scrollTo({
      top: targetScrollTop,
      behavior: "smooth",
    });
  });
});

// 移动端设备-产品中心 设备切换
// 初始化菜单滑动
const menuSwiper = new Swiper(".menu-swiper", {
  slidesPerView: "auto",
  spaceBetween: 10,
  freeMode: true,
});

// 初始化产品展示滑动
const productSwiper = new Swiper(".products-swiper", {
  slidesPerView: 1,
  spaceBetween: 30,
  pagination: {
    el: ".swiper-pagination",
    clickable: true,
  },
  breakpoints: {
    768: {
      slidesPerView: 3,
    },
    1024: {
      slidesPerView: 4,
    },
  },
});

// 菜单点击事件
let getTemplateMobile = (title) => {
  return `<div class="swiper-slide">
              <div class="m-product-card">
                <div class="m-product-image">
                  <img src="/assets/image/index/p.png" alt="ZY/ZX32螺旋榨油机">
                </div>
                <div class="m-product-info">
                  <h3>${title}ZY/ZX32螺旋榨油机</h3>
                  <div>
                    ZY/ZX32螺旋榨油机是大型连续榨油设备，适用于棉籽、菜籽、蓖麻、葵花籽、花生等高含油料的压榨制油，具有处理量大、动力消耗小、运行费用低、榨出饼结构松而不碎、易于溶剂渗透、残油率低等特点。
                  </div>
                </div>
              </div>
            </div>

            <div class="swiper-slide">
              <div class="m-product-card">
                <div class="m-product-image">
                  <img src="https://24666205.s21i.faiusr.com/2/ABUIABACGAAghpLZmgYom5HMHjCgBjigBg!400x400.jpg"
                    alt="​YZCL系列蒸炒锅">
                </div>
                <div class="m-product-info">
                  <h3>${title}​YZCL系列蒸炒锅</h3>
                  <div>
                    YZCL系列蒸炒锅是将轧坯后的生坯经润湿、蒸炒而制成熟坯的加工设备，以满足后序榨油的工艺要求。本设备亦可兼作软化锅使用，油料经过软化可提高轧坯质量，进而提高出油率，并可改善毛油质量，是植物油厂用于植物油料预处理的主要设备之一。
                  </div>
                </div>
              </div>
            </div>

            <div class="swiper-slide">
              <div class="m-product-card">
                <div class="m-product-image">
                  <img src="https://24666205.s21i.faiusr.com/2/ABUIABACGAAg7JHZmgYotI2SrQQwoAY4oAY!400x400.jpg"
                    alt="ZX10系列螺旋榨油机">
                </div>
                <div class="m-product-info">
                  <h3>${title}ZX10系列螺旋榨油机</h3>
                  <div>
                    2X10系列螺旋榨油机适用于各种植物油料的压榨制油，该设备结构紧凑，占地面积小，动力消耗小。特别适用于浓香料、稀有油料等油料的油脂制取。
                  </div>
                </div>
              </div>
            </div>`;
};
const menuItems = document.querySelectorAll(".menu-swiper .swiper-slide");
menuItems.forEach((item, index) => {
  item.addEventListener("click", () => {
    menuItems.forEach((i) => i.classList.remove("active"));
    item.classList.add("active");
    // 这里可以添加切换产品类别的逻辑
    document.querySelector(".swiper-wrapper-mobile").innerHTML=getTemplateMobile(item.innerText);
    // 获取必要的尺寸信息
    const swiperWidth = menuSwiper.el.offsetWidth;
    const slideWidth = item.offsetWidth;
    const slideLeft = item.offsetLeft;

    // 计算目标滚动位置（使当前slide居中）
    let targetPosition = slideLeft - swiperWidth / 2 + slideWidth / 2;

    // 获取所有slides的总宽度
    const totalWidth = Array.from(menuItems).reduce(
      (sum, slide) => sum + slide.offsetWidth + 10,
      0
    ); // 10是spaceBetween的值
    const maxScroll = totalWidth - swiperWidth;

    // 特殊处理最后一个菜单项
    if (index === menuItems.length - 1) {
      targetPosition = maxScroll;
    }

    // 确保不会超出边界
    targetPosition = Math.max(0, Math.min(targetPosition, maxScroll));

    // 使用translateTo进行平滑滚动
    menuSwiper.translateTo(-targetPosition, 300);
  });
});
